package com.egu.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.egu.mapper.CustomerConditionMapper;
import com.egu.model.CustomerCondition;
import com.egu.model.CustomerConditionExample;
import com.egu.model.CustomerConditionExample.Criteria;
import com.egu.service.CustomerConditionService;
import com.egu.vo.PageParam;
import com.egu.vo.RequestPageVo;
import com.egu.vo.RequestResultVo;

@Service
public class CustomerConditionServiceImple implements CustomerConditionService {

	@Autowired
	CustomerConditionMapper customerConditionMapper;

	public RequestPageVo<CustomerCondition> getList(PageParam param, CustomerCondition customerCondition) {
		RequestPageVo<CustomerCondition> result = new RequestPageVo<CustomerCondition>();
		CustomerConditionExample example = new CustomerConditionExample();
		Criteria criteria = example.createCriteria();
		criteria.andIsUsedEqualTo("1");
		if (StringUtils.isNotBlank(customerCondition.getConditionName())) {
			criteria.andConditionNameLike("%" + customerCondition.getConditionName() + "%");
		}
		int count = (int) customerConditionMapper.countByExample(example);
		if (count > 0) {
			example.setStartPage(param.getOffset());
			example.setPageSize(param.getLimit());
			List<CustomerCondition> list = customerConditionMapper.selectByExample(example);
			result.setRows(list);
			result.setTotal(count);
		}
		return result;
	}

	@Override
	public RequestResultVo<List<CustomerCondition>> getAllList() {
		CustomerConditionExample example = new CustomerConditionExample();
		example.createCriteria().andIsUsedEqualTo("1");
		List<CustomerCondition> list = customerConditionMapper.selectByExample(example);
		return RequestResultVo.success(list);
	}

	@Override
	@Transactional
	public RequestResultVo<CustomerCondition> saveOrUpdate(CustomerCondition customerCondition) {
		if (customerCondition.getId() == null) {
			customerConditionMapper.insertSelective(customerCondition);
		} else {
			customerConditionMapper.updateByPrimaryKeySelective(customerCondition);
		}
		return RequestResultVo.success();
	}

	@Override
	@Transactional
	public RequestResultVo<CustomerCondition> deleteDataById(Integer id) {
		CustomerCondition customerCondition = new CustomerCondition();
		customerCondition.setId(id);
		customerCondition.setIsUsed("0");
		try {
			customerConditionMapper.updateByPrimaryKeySelective(customerCondition);
		} catch (Exception e) {
			return RequestResultVo.error("数据库删除失败");
		}
		return RequestResultVo.success();
	}

}
